package net.bblot.lottery.api.request;

import android.content.Context;
import android.os.Build;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.webkit.WebView;

import net.bblot.lottery.PackegeConfig;
import net.bblot.lottery.activity.QApplication;
import net.bblot.lottery.api.ApiClinet;
import net.bblot.lottery.api.ApiResponseListener;
import net.bblot.lottery.api.SimpleResponseListener;
import net.bblot.lottery.api.bean.ResponseWebUpdate;
import net.bblot.lottery.api.result.ExcuterResult;
import net.bblot.lottery.api.task.HttpTask;
import net.bblot.lottery.util.AppConfig;
import net.bblot.lottery.util.FileDownLoader;
import net.bblot.lottery.util.FileUtil;
import net.bblot.lottery.util.Logger;
import net.bblot.lottery.util.Md5Utils;
import net.bblot.lottery.util.ZipUtil;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by feng on 2017/9/8.
 *
 * 该类用于从服务器下载最新的web部分的zip压缩包（assets中的所有web相关的文件），并解压到/data/data/packagename/app_web目录
 *
 */

public class GetWebUpdate {
    public static final String TAG = "GetWebUpdate";

    public static HttpTask getUpdate(Context context, ApiResponseListener listener) {
        String url = PackegeConfig.Base_url + "/api/system/AppInfo/getapp";
//        ParamWebUpdate paramWebUpdate = new ParamWebUpdate();
//        paramWebUpdate.setAppVersion(AppConfig.getCurrentAppVersion(context));
//        paramWebUpdate.setAppKey(PackegeConfig.App_key);
//        paramWebUpdate.setCurVersion(AppConfig.getWebVersion(context));
//        paramWebUpdate.setChannelId(AppConfig.getAppMetaData(context, "STATION_ID"));
//        paramWebUpdate.setOs("android");
//        paramWebUpdate.setOsVersion(Build.VERSION.RELEASE);
//        paramWebUpdate.setPackageName(context.getPackageName());
//        paramWebUpdate.setUa(new WebView(context).getSettings().getUserAgentString());
//
//        Gson gson = new Gson();
//        String content = gson.toJson(paramWebUpdate);
//        JSONObject jsonObject = new JSONObject();
//        try {
//            jsonObject.put("para", content);
//        } catch (JSONException e) {
//            e.printStackTrace();
//        }

        List<NameValuePair> pairs = new ArrayList<>();
        pairs.add(new BasicNameValuePair("curVersion", AppConfig.getWebVersion(context)));
        pairs.add(new BasicNameValuePair("appVersion", AppConfig.getCurrentAppVersion(context)));
        pairs.add(new BasicNameValuePair("appKey", PackegeConfig.App_key));
        pairs.add(new BasicNameValuePair("packageName", context.getPackageName()));
        pairs.add(new BasicNameValuePair("channelId", AppConfig.getAppMetaData(context, "STATION_ID")));//channelId
        pairs.add(new BasicNameValuePair("os", "android"));
        pairs.add(new BasicNameValuePair("osVersion", Build.VERSION.RELEASE));
        pairs.add(new BasicNameValuePair("ua", new WebView(context).getSettings().getUserAgentString()));

        final Handler handler = HttpTask.getHttpHandler(listener);
        return HttpTask.getTask(handler, context, url, HttpTask.HTTP_REQEST_TYPE_GET, pairs, null, null, null);
       // return HttpTask.getPostTask(handler, context, url, jsonObject.toString());
    }

    public static void checkWebUpdate(final Context context, final UpdateListener updateListener) {
        //网络访问结果监听
        SimpleResponseListener listener = new SimpleResponseListener() {
            @Override
            public void onGetResult(String responsCode, @NonNull ExcuterResult er) {
                String result = er.getResult();

//                测试
//                JSONObject jsonObject = new JSONObject();
//                try {
//                    jsonObject.put("code", "0000");
//                    jsonObject.put("code_str", "suc");
//                    JSONObject info = new JSONObject();
//                    JSONObject pkg = new JSONObject();
//                    pkg.put("hot_down_url", "http://192.168.1.157:8080/MyWeb/www.zip");
//                    pkg.put("hot_version", "1.0.1");
//                    pkg.put("hot_md5", "f624bfc88e7ad0f6a8609278c6a46d7e");
//                    info.put("package", pkg);
//                    jsonObject.put("info", info);
//                } catch (JSONException e) {
//                    e.printStackTrace();
//                }
//                result = jsonObject.toString();
//                测试

                Logger.e(TAG, "版本信息：" + result);
                if (!TextUtils.isEmpty(result)) {
                    //根据返回的json数据解析成相应的对象
                    ResponseWebUpdate responseWebUpdate = parse(result, context);
                    if (responseWebUpdate != null) {
                        //如果有更新
                        if ("yes".equals(responseWebUpdate.getStatus()) || !isIndexPageReady()) {
                            Logger.e(TAG, "有更新");
                            //下载更新包
                            download(context, responseWebUpdate, updateListener);
                            return;
                        }

                    }
                }
                updateListener.onFinish(UpdateListener.RES_NO_UPDATE);
            }

            @Override
            public void onWrongResponse(String responsCode, ExcuterResult er) {
                updateListener.onFinish(UpdateListener.RES_NET_ERROR);
            }
        };
        HttpTask task = GetWebUpdate.getUpdate(context.getApplicationContext(), listener);
        ApiClinet.getInstance().doHttpTask(task, listener);
    }

    private static boolean isIndexPageReady() {
        List<File> files = FileUtil.searchFile(AppConfig.getWebRootDir(QApplication.context), PackegeConfig.INDEX_PAGE);
        return FileUtil.checkAssetsFileExit("www/" + PackegeConfig.INDEX_PAGE) || files.size() > 0;
    }

    private static ResponseWebUpdate parse(String content, Context context) {
        try {
            JSONObject jsonObject = new JSONObject(content);
            JSONObject info = jsonObject.optJSONObject("info");
            if (info != null) {
                ResponseWebUpdate responseWebUpdate = new ResponseWebUpdate();
                JSONObject packageInfo = info.optJSONObject("package");
                //版本号
                String version = packageInfo.optString("hot_version");
                //下载url
                String url = packageInfo.optString("hot_down_url");
                //文件md5
                String md5 = packageInfo.optString("hot_md5_down");

                responseWebUpdate.setVersion(version);
                responseWebUpdate.setUrl(url);
                responseWebUpdate.setFileMD5(md5);

                if (compareVersion(AppConfig.getWebVersion(context), version)) {
                    responseWebUpdate.setStatus("yes");
                }
                return responseWebUpdate;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private static void download(final Context context, final ResponseWebUpdate responseWebUpdate, final UpdateListener updateListener) {
        final String path = getDownloadPath(context);
        FileDownLoader fileDownLoader = FileDownLoader.getInstance();
        FileDownLoader.DownLoadListener listener = new FileDownLoader.DownLoadListener() {
            @Override
            public void onFileDownLoadResult(String filePath, boolean down_ok) {
                Logger.e(TAG, "文件下载结束" + down_ok);
                updateListener.onDownloadEnd(down_ok);
                File downloadedFile = new File(filePath);
                boolean isOk = false;
                int resultCode = -1;
                if (down_ok) {
                    //下载成功，比较文件md5
                    String md5 = Md5Utils.getFileMD5(downloadedFile);
                    if (!TextUtils.isEmpty(md5) && md5.equalsIgnoreCase(responseWebUpdate.getFileMD5())) {
                        String unzipPath = context.getDir("web", Context.MODE_PRIVATE).getAbsolutePath() + File.separator + responseWebUpdate.getVersion();
                        String tempUnzipPath = unzipPath + "_temp";
                        File unzipFile = new File(unzipPath);
                        File tempUnzipFile = new File(tempUnzipPath);
                        //删除历史解压目录
                        FileUtil.deleteAllFile(unzipFile);
                        FileUtil.deleteAllFile(tempUnzipFile);
                        //开始解压
                        updateListener.onUnzipStart();
                        isOk = unZipFile(context, filePath, tempUnzipPath);
                        updateListener.onUnzipEnd(isOk);
                        if (isOk) {
                            if (FileUtil.searchFile(tempUnzipPath, PackegeConfig.INDEX_PAGE).size() > 0) {
                                try {
                                    //删除历史版本的web
                                    FileUtil.deleteAllFile(new File(AppConfig.getWebRootDir(context)));
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                                tempUnzipFile.renameTo(unzipFile);
                                //设置新的web版本号
                                AppConfig.saveWebVersion(context, responseWebUpdate.getVersion());
                                //设置新的web加载根路径
                                AppConfig.saveWebRootDir(context, unzipPath);
                                resultCode = UpdateListener.RES_SUCCESS;
                            } else {
                                resultCode = UpdateListener.RES_FILE_NOT_FOUND;
                            }
                        } else {
                            //解压失败，删除解压的目录
                            resultCode = UpdateListener.RES_UNZIP_FAIL;
                            FileUtil.deleteAllFile(unzipFile);
                        }
                    } else {
                        resultCode = UpdateListener.RES_MD5_MISMATCH;
                    }
                } else {
                    resultCode = UpdateListener.RES_DOWNLOAD_FAIL;
                }
                //删除压缩包
                FileUtil.deleteAllFile(downloadedFile);
                updateListener.onFinish(resultCode);
            }

            @Override
            public void onPercentUpdate(int per) {
                Logger.e(TAG, "文件下载进度：" + per + "%");
                updateListener.onDownloadPercent(per);
            }
        };
        fileDownLoader.addDownLoadListener(listener);
        fileDownLoader.downLoad(context.getApplicationContext(), responseWebUpdate.getUrl(), "www.zip", path);
        updateListener.onDownloadStart();
    }

    private static boolean unZipFile(Context context, String filePath, String dir) {
        return ZipUtil.unZipFile(context, filePath, dir);
    }

    public static String getDownloadPath(Context context) {
        String path = null;
        if (context.getExternalCacheDir() != null) {
            path = context.getExternalCacheDir().getAbsolutePath();
        }
        if (!FileUtil.checkFileExit(path)) {
            path = context.getDir("download", Context.MODE_PRIVATE).getAbsolutePath();
        }

        return path;
    }

    private static boolean compareVersion(String v1, String v2) {
        try {
            String[] subVers1 = v1.split("\\.");
            String[] subVers2 = v2.split("\\.");
            for (int i = 0; i< subVers1.length; i++) {
                int subVerInt1 = Integer.parseInt(subVers1[i]);
                int subVerInt2 = Integer.parseInt(subVers2[i]);
                if (subVerInt1 < subVerInt2) {
                    return true;
                } else if (subVerInt1 > subVerInt2) {
                    return false;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public interface UpdateListener {
        int RES_NO_UPDATE = 1001;
        int RES_DOWNLOAD_FAIL = 1002;
        int RES_MD5_MISMATCH = 1003;
        int RES_UNZIP_FAIL = 1004;
        int RES_FILE_NOT_FOUND = 1005;
        int RES_NET_ERROR = 1006;
        int RES_SUCCESS = 1007;

        void onDownloadStart();
        void onDownloadPercent(int per);
        void onDownloadEnd(boolean result);
        void onUnzipStart();
        void onUnzipEnd(boolean result);
        void onFinish(int result);
    }

    public static class SimpleUpdateListener implements UpdateListener {

        @Override
        public void onDownloadStart() {

        }

        @Override
        public void onDownloadPercent(int per) {

        }

        @Override
        public void onDownloadEnd(boolean result) {

        }

        @Override
        public void onUnzipStart() {

        }

        @Override
        public void onUnzipEnd(boolean result) {

        }

        @Override
        public void onFinish(int result) {

        }
    }

}
